const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require("../../models/User");
const passport = require("passport");

//GET api/users/test

// router.get("/test",(req,res) =>{
//     res.json({msg:"login work"})
// })

//POST api/users/register

router.post("/register",(req,res) =>{
    console.log(req.body);

    //查询数据库中是否有邮箱
    User.findOne({username:req.body.username})
        .then((user)=>{
            if(user){
                return res.status(400).json({username:"用户名已注册已被注册"})
            }else{

                var avatar = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimages.669pic.com%2Felement_pic%2F6%2F84%2F58%2F74%2Ffb86f2dc61c757a8a0ab79fb8e343fec.jpg%21w700wb&refer=http%3A%2F%2Fimages.669pic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1659688642&t=65d18985abcac4f8af34663b64aea27c";

                const newUser = new User({
                    name:req.body.name,
                    username:req.body.username,
                    avatar,
                    password:req.body.password,
                    identity:req.body.identity
                })

                newUser.save()
                        .then(user => res.json(user))
                        .catch(err => console.log(err));
                
            }
        })
})


//POST api/users/login
//返回token jwt passport

router.post("/login",(req, res) =>{
    const username = req.body.username;
    const password = req.body.password;
    // 查询数据库
    User.findOne({username})
        .then(user =>{
            if(!user){
                return res.status(404).json("用户不存在")
            }
            // 密码匹配
            if(password == user.password){
                const rule = {id:user.id,name:user.name,avatar:user.avatar,identity:user.identity};
                jwt.sign(rule,"secret",{expiresIn:3600},(err, token)=>{
                    if(err) throw err;
                    res.json({
                        success:true,
                        token:"Bearer "+token
                    })
                })
            }else{
                return res.status(400).json("密码错误");
            }
        })
})


//GET api/users/current
//返回 current userInfo
router.get("/current",passport.authenticate("jwt",{session:false}),(req, res) =>{
    // res.json({msg:"success"})
    res.json({
        id: req.user.id,
        name: req.user.name,
        username: req.user.username,
        identity: req.user.identity
    });
})

//GET api/users/userlist
router.get("/list",passport.authenticate("jwt",{session:false}),(req, res) =>{
    User.find()
    .then(user =>{
        if(!user){
            return res.status(404).json('没有任何内容');
        }
        res.json(user);
    })
    .catch(err =>res.status(404).json(err));
})

   
module.exports = router;